package com.example.cd5160866.urlapp.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ImageUtil {
    public final static int MAX_SIZE = 800;

    /**
     * @param imagepath     图片的物理路径
     * @param realImageSize 图片的实际长宽
     * @return
     */
    public static Bitmap getBitmapTransform(String imagepath, int realImageSize) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagepath, options);
        if (options.outWidth == 0 || options.outHeight == 0) {
            return null;
        }

        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, realImageSize, realImageSize);
        return BitmapFactory.decodeFile(imagepath, options); // 这里注意得到的如果是1/3会变成1/2分母永远是2的平方

    }

    /**
     * Figure out what ratio we can load our image into memory at while still
     * being bigger than our desired width and height
     *
     * @param srcWidth
     * @param srcHeight
     * @param dstWidth
     * @param dstHeight
     * @return
     */
    public static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
        final float srcAspect = (float) srcWidth / (float) srcHeight;
        final float dstAspect = (float) dstWidth / (float) dstHeight;

        if (srcAspect > dstAspect) {
            return srcWidth / dstWidth;
        } else {
            return srcHeight / dstHeight;
        }
    }

    public static Bitmap getBitmapFromCamera(Context context, String filePath, Intent intent, int maxSize) {
        Bitmap bitmaptemp = ImageUtil.getBitmapTransform(filePath, MAX_SIZE);
        if (bitmaptemp == null && intent.getExtras() != null) {
            // Try to get the bitmap from intent.
            bitmaptemp = (Bitmap) intent.getExtras().get("data");
        }
        if (bitmaptemp == null)
            return null;
        return getPerfectBitmap(bitmaptemp, maxSize);
    }

    public static Bitmap getBitmapFromCamera(Context context, String filePath, Intent intent) {
        return getBitmapFromCamera(context, filePath, intent, MAX_SIZE);
    }

    static Bitmap getPerfectBitmap(Bitmap sourceBitmap, int maxSize) {
        Bitmap bitmap;
        if (sourceBitmap.getWidth() > maxSize || sourceBitmap.getHeight() > maxSize) {
            if (sourceBitmap.getWidth() >= sourceBitmap.getHeight()) {
                float beli = sourceBitmap.getWidth() / ((float) maxSize);
                int heighttemp = (int) (sourceBitmap.getHeight() / beli);

                bitmap = ThumbnailUtils.extractThumbnail(sourceBitmap, maxSize, heighttemp);
            } else {
                float beli = sourceBitmap.getHeight() / ((float) maxSize);
                int widthtemp = (int) (sourceBitmap.getWidth() / beli);
                bitmap = ThumbnailUtils.extractThumbnail(sourceBitmap, widthtemp, maxSize);
            }
            /**
             * 因为bitmap = ThumbnailUtils.extractThumbnail(bitmaptemp, 1024,
             * heighttemp);中的bitmaptemp和bitmap已经不是指向 同一个内存区域，所以需要回收bitmaptemp。
             * */
            if (sourceBitmap != null && !sourceBitmap.isRecycled()) {
                sourceBitmap.recycle();
            }
        } else {
            bitmap = sourceBitmap;
        }
        return bitmap;
    }

    //	public static void getB(Activity context, Intent data) {
    //		Bitmap bm = null;
    //
    //		// 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
    //
    //		ContentResolver resolver = context.getContentResolver();
    //
    //		// 此处的用于判断接收的Activity是不是你想要的那个
    //
    //		try {
    //
    //			Uri originalUri = data.getData(); // 获得图片的uri
    //
    //			bm = MediaStore.Images.Media.getBitmap(resolver, originalUri); // 显得到bitmap图片
    //
    //			// 这里开始的第二部分，获取图片的路径：
    //
    //			String[] proj = { MediaStore.Images.Media.DATA };
    //
    //			// 好像是android多媒体数据库的封装接口，具体的看Android文档
    //
    //			Cursor cursor = context.managedQuery(originalUri, proj, null, null, null);
    //
    //			// 按我个人理解 这个是获得用户选择的图片的索引值
    //
    //			int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    //
    //			// 将光标移至开头 ，这个很重要，不小心很容易引起越界
    //
    //			cursor.moveToFirst();
    //
    //			// 最后根据索引值获取图片路径
    //
    //			String path = cursor.getString(column_index);
    //			DevUtil.d("zqt", "path=" + path);
    //			DevUtil.d("zqt", "bm=" + bm.getWidth() + "-" + bm.getHeight());
    //		} catch (IOException e) {
    //			DevUtil.e("zqt", e);
    //		}
    //
    //	}
    public static Bitmap getBitmapFromAlbum(Context context, Intent data) {
        return getBitmapFromAlbum(context, data, MAX_SIZE);
    }

    public static Bitmap getBitmapFromAlbum(Context context, Intent data, int maxSize) {
        Bitmap bitmap = ImageUtil.getBitmapFromAlbumByFilePath(context, data);
        if (bitmap == null) {
            try {
                bitmap = Media.getBitmap(context.getContentResolver(), data.getData());
                bitmap = getPerfectBitmap(bitmap, maxSize);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    public static int getImageOrientation(Context context, Uri uri) {
        int rotate = 0;
        String[] cols = {MediaStore.Images.Media.ORIENTATION};
        try {
            Cursor cursor = context.getContentResolver().query(uri,
                    cols, null, null, null);
            if (cursor != null) {
                cursor.moveToPosition(0);
                rotate = cursor.getInt(0);
                cursor.close();
            }
        } catch (Exception e) {
            // You can get an IllegalArgumentException if ContentProvider doesn't support querying for orientation.
        }
        return rotate;
    }

    public static Bitmap getBitmapFromAlbumByFilePath(Context context, Intent data) {
        return getBitmapFromAlbumByFilePath(context, data, MAX_SIZE);
    }

    public static Bitmap getBitmapFromAlbumByFilePath(Context context, Intent data, int maxSize) {
        Uri originalUri = data.getData();
        ContentResolver resolver = context.getContentResolver();
        if (resolver == null || originalUri == null) {
            return null;
        }
        Cursor cursor = resolver.query(originalUri, null, null, null, null);
        if (cursor == null || cursor.getCount() <= 0) {
            return null;
        }
        cursor.moveToFirst();

        int column = cursor.getColumnIndex(MediaStore.Images.Media.DATA);

        if (column < 0) {
            /**
             * 如果不能cursor.getColumnIndex(MediaStore.Images.Media.DATA)获取的缓存数据，
             * 可以通过下面方式获取图片。
             * 这样获取不到文件的路径，所以需要document_id获取文件id。然后拼接到content://media
             * /external/images/media/后面获取图片路径。
             * */
            // bitmaptemp =
            // BitmapFactory.decodeStream(getContentResolver().openInputStream(originalUri));

            int columntemp = cursor.getColumnIndex("document_id");
            String imageId = "" + cursor.getString(columntemp);
            if (imageId == null || !imageId.contains("image:")) {
                // mProgressBar.setVisibility(View.GONE);
                return null;
            }
            imageId = "content://media/external/images/media/" + imageId.substring(6);
            Uri uri = Uri.parse(imageId);
            resolver = context.getContentResolver();
            if (resolver == null || uri == null) {
                // mProgressBar.setVisibility(View.GONE);
                return null;
            }
            cursor = resolver.query(uri, null, null, null, null);
            if (cursor == null || cursor.getCount() <= 0) {
                // mProgressBar.setVisibility(View.GONE);
                return null;
            }
            cursor.moveToFirst();

            column = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
            if (column < 0) {
                // mProgressBar.setVisibility(View.GONE);
                return null;
            }
        }

        String imagePath = cursor.getString(column);
        // upLoadImage = imagePath;
        return getPerfectBitmap(ImageUtil.getBitmapTransform(imagePath, maxSize), maxSize);
    }

    private static void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[512];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

}
